package com.javandad.app.client.project;

import java.util.List;

import com.google.gwt.cell.client.AbstractCell;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.user.cellview.client.CellList;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AbsolutePanel;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SelectionChangeEvent.Handler;
import com.google.gwt.view.client.SingleSelectionModel;
import com.javandad.app.shared.entity.User;
import com.javandad.app.shared.entity.project.ProjectAssoc;


public class AssociatesTab extends AbsolutePanel {

	/**
	 * @wbp.parser.constructor
	 */
	public AssociatesTab(ProjectServiceAsync projectService,
			String projectName, String username, boolean owner) {

		this.projectService = projectService;
		this.projectName = projectName;
		this.username = username;
		this.owner = owner;
		
		class AssocUserCell extends AbstractCell<User> {

			@Override
			public void render(com.google.gwt.cell.client.Cell.Context context, User value, SafeHtmlBuilder sb) {
				// TODO
				sb.appendEscaped(value.getFirstName() + " "
						+ value.getLastName() + "( " + value.getUsername()
						+ " )");
				sb.appendHtmlConstant("<a href='home.jsp?view="
						+ value.getUsername() + "'>view</a>");
			}
			
		}
		AssocUserCell userCell = new AssocUserCell();

		this.setSize("914px", "800px");
		cellList = new CellList<User>(userCell);

		add(cellList, 10, 46);
		cellList.setSize("736px", "216px");

		cellList_1 = new CellList<User>(userCell);

		final SingleSelectionModel<User> sm_1 = new SingleSelectionModel<User>();
		cellList_1.setSelectionModel(sm_1);
		sm_1.addSelectionChangeHandler(new Handler() {

			@Override
			public void onSelectionChange(SelectionChangeEvent event) {
				textBox.setText(sm_1.getSelectedObject().getUsername());
				checkAssociationForGUIUpdate();

			}

		});

		add(cellList_1, 10, 315);
		cellList_1.setSize("736px", "252px");

		Label lblOwners = new Label("Owners");
		add(lblOwners, 10, 25);

		Label lblMembers = new Label("Members");
		add(lblMembers, 10, 294);

		if (owner) {
			btnAdd = new Button("invite");
			btnFire = new Button("Remove");
			btnAdd.addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					sendParticipationInvitation();
				}
			});

			btnAdd.setEnabled(false);
			btnAdd.setText("invite");
			add(btnAdd, 659, 583);
			btnAdd.setSize("87px", "26px");
			btnFire.addClickHandler(new ClickHandler() {
				public void onClick(ClickEvent event) {
					removeParticipation();
				}
			});

			btnFire.setEnabled(false);
			btnFire.setText("Remove");
			add(btnFire, 578, 583);
			btnFire.setSize("73px", "26px");
			textBox.addKeyUpHandler(new KeyUpHandler() {
				public void onKeyUp(KeyUpEvent event) {
					checkAssociationForGUIUpdate();
				}
			});

			add(textBox, 83, 585);
			textBox.setSize("428px", "24px");

			Label lblUsername = new Label("Username");
			add(lblUsername, 8, 594);
		}
	}

	protected void onLoad() {
		super.onLoad();

		getAssociates(projectName, ProjectAssoc.OWNING_PROJECT, cellList);
		getAssociates(projectName, ProjectAssoc.PARTICIPATING_PROJECT,
				cellList_1);

	}

	private void getAssociates(String projectName, int level,
			final CellList<User> list) {
		projectService.getUsers(projectName, level,
				new AsyncCallback<List<User>>() {

					@Override
					public void onSuccess(List<User> result) {
						list.redraw();
						list.setRowData(result);
					}

					@Override
					public void onFailure(Throwable caught) {
						caught.printStackTrace();
					}
				});
	}

	private void sendParticipationInvitation() {
		projectService.sendParticipationInvitation(projectName, textBox
				.getText(), new AsyncCallback<Boolean>() {

			@Override
			public void onFailure(Throwable caught) {
			}

			@Override
			public void onSuccess(Boolean result) {
				if (result) {
					Window.alert("An invitation just sent to "
							+ textBox.getText());
					getAssociates(projectName,
							ProjectAssoc.PARTICIPATING_PROJECT, cellList_1);
					btnAdd.setEnabled(false);
					btnFire.setEnabled(true);

				} else {
					Window.alert("One of the following problems has been occured : \n 1. The recipient may not be a valid user. \n 2. The recipient is already a member. \n 3. The recipient has already been invited.");
				}

			}
		});
	}

	private void checkAssociationForGUIUpdate() {
		projectService
				.getThisAssociationAmongAllIncludingUnconfirmedInvitations(
						projectName, textBox.getText(),
						ProjectAssoc.PARTICIPATING_PROJECT,
						new AsyncCallback<ProjectAssoc>() {

							@Override
							public void onFailure(Throwable caught) {
							}

							@Override
							public void onSuccess(ProjectAssoc result) {
								if (result == null) {
									btnAdd.setEnabled(true);
									btnFire.setEnabled(false);
								} else {
									btnAdd.setEnabled(false);
									btnFire.setEnabled(true);
								}

							}
						});

	}

	private void removeParticipation() {
		projectService.removeParticipation(projectName, textBox.getText(),
				new AsyncCallback<Boolean>() {

					@Override
					public void onFailure(Throwable caught) {
					}

					@Override
					public void onSuccess(Boolean result) {
						if (result) {
							Window.alert("User just removed!");
							checkAssociationForGUIUpdate();
							getAssociates(projectName,
									ProjectAssoc.PARTICIPATING_PROJECT,
									cellList_1);
						} else {

							Window.alert("One of the following problems has been occured : \n 1. The recipient may not be a valid user. \n 2. The recipient is not a member.");
						}

					}
				});
	}

	private String projectName = "";
	@SuppressWarnings("unused")
	private String username;
	@SuppressWarnings("unused")
	private boolean owner;
	private ProjectServiceAsync projectService;
	private CellList<User> cellList;
	private CellList<User> cellList_1;
	private TextBox textBox = new TextBox();
	private Button btnFire ;
	private Button btnAdd ;

}
